import json
import requests

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.http import StreamingHttpResponse
from django.conf import settings  # 从settings获取API密钥


# Create your views here.
# book/views.py
class AIContinueAPIView(APIView):
    def post(self, request):
        user_text = request.data.get('text', '')
        
        payload = {
            "model": "Qwen/Qwen2.5-7B-Instruct",
            "messages": [
                {
                    "role": "system",
                    "content": "你是一个专业的小说续写助手，对一篇未完成的文章进行续写完成剩余部分，请严格遵循以下规则：1.直接从文章已完成的部分结束的位置开始续写内容。2.不要添加解释、分析或其他内容或重复之前的内容。3.保持连贯且符合设定。"
                },
                {
                    "role": "user",
                    "content": "文章已完成的部分：" + user_text
                },
            ],
            "stream": True,  # 启用流式传输
            "max_tokens": 512,
            "temperature": 0.7,
            "top_p": 0.7,
            "top_k": 50,
            "frequency_penalty": 0.5,
            "n": 1,
            "response_format": { "type": "text" }
        }

        headers = {
                    "Authorization": f"Bearer {settings.SILICONFLOW_API_KEY}",
                    "Content-Type": "application/json"
                }

        try:
            response = requests.post(
                "https://api.siliconflow.cn/v1/chat/completions",
                headers=headers,
                json=payload,
                stream=True
            )
            response.raise_for_status()

            def generate():
                try:
                    for chunk in response.iter_lines():
                        if chunk:
                            decoded_line = chunk.decode('utf-8').strip()
                            # 处理每行数据的前缀
                            if decoded_line.startswith('data: '):
                                json_str = decoded_line[6:]  # 去掉"data: "
                                if json_str == '[DONE]':
                                    break  # 结束流
                                try:
                                    data = json.loads(json_str)
                                    # 提取内容
                                    content = data.get("choices", [{}])[0].get("delta", {}).get("content", "")
                                    # 仅当content非空且包含实际文本时才发送
                                    if content and content.strip():
                                        yield f"data: {json.dumps({'chunk': content}, ensure_ascii=False)}\n\n"
                                except json.JSONDecodeError:
                                    yield f"event: error\ndata: {json.dumps({'error': '数据解析失败'})}\n\n"
                                    break
                    yield "data: {\"chunk\": \"DONE\"}\n\n"
                except Exception as e:
                    yield f"event: error\ndata: {json.dumps({'error': '流式传输中断'})}\n\n"

            return StreamingHttpResponse(
                generate(),
                content_type='text/event-stream'
            )

        except requests.exceptions.RequestException as e:
            return Response(
                {"error": f"AI服务请求失败: {str(e)}"},
                status=status.HTTP_503_SERVICE_UNAVAILABLE
            )


class AIGrammarCheckAPIView(APIView):
    def post(self, request):
        user_text = request.data.get('text', '')
        
        payload = {
            "model": "Qwen/Qwen2.5-7B-Instruct",
            "messages": [
                {
                    "role": "system",
                    "content": """你是一个专业的语法检查助手，请严格遵循以下规则：
1. 检查用户提供的文本中的语法和标点符号错误
2. 按出现顺序列出所有错误
3. 每个错误需包含：
   - 错误在原文中的具体原句
   - 错误类型
   - 错误内容（错误单词/短语）
   - 修正建议
4. 使用JSON格式返回，格式示例：
{
  "errors": [
    {
      "sentence": "He likes apples",  # 包含错误的完整句子
      "content": "likes",            # 错误单词
      "type": "主谓不一致",
      "suggestion": "like"
    }
  ]
}"""
                },
                {
                    "role": "user",
                    "content": user_text
                },
            ],
            "temperature": 0.3,
            "max_tokens": 1024,
            "response_format": { "type": "json_object" }
        }

        headers = {
            "Authorization": f"Bearer {settings.SILICONFLOW_API_KEY}",
            "Content-Type": "application/json"
        }

        try:
            # 发送普通请求（非流式）
            response = requests.post(
                "https://api.siliconflow.cn/v1/chat/completions",
                headers=headers,
                json=payload
            )
            response.raise_for_status()

            # 解析完整响应
            result = response.json()
            content = result['choices'][0]['message']['content']
            
            try:
                # 直接返回语法检查结果
                grammar_result = json.loads(content)
                return Response(grammar_result)
            except json.JSONDecodeError:
                return Response(
                    {"error": "语法检查结果解析失败"},
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR
                )

        except requests.exceptions.RequestException as e:
            return Response(
                {"error": f"语法检查服务不可用: {str(e)}"},
                status=status.HTTP_503_SERVICE_UNAVAILABLE
            )